﻿using System;
using System.Linq;
using db = DataContext;

namespace WebApplication.admin
{
	public partial class News : System.Web.UI.Page
	{
		public bool isadd, isdelete, issave;

		public int start, limit;

		public int id = 0;
	
		protected void Page_Load(object sender, EventArgs e)
		{
			Common.CheckLogin();

			isadd = Common.IsEdit;
			isdelete = Common.IsDelete;
			issave = Common.IsSave;

			start = Common.Start;
			limit = n_pager.Limit;

			id = Common.Id;
			
			
			using (db.DbDataContext context = new db.DbDataContext())
			{
				if (isadd)
				{
					if (id > 0)
					{
						lit_action.Text = "编辑";
						btn_save.Value = "保存";

						db.News news = context.News.Single(x => x.Id == id);
						title.Value = news.Title;
						tags.Value = news.Keywords;
						content.Value = news.Content;
					}
				}

				if (isdelete)
				{
					context.News.DeleteOnSubmit(context.News.Single(x => x.Id == id));
					context.SubmitChanges();
					Response.Redirect("news.aspx?start=" + start + "&limit=" + limit, true);
				}

				if (issave)
				{
					if (id > 0)
					{
						db.News news = context.News.Single(x => x.Id == id);
						news.Title = Request.Form["title"].Trim();
						news.Keywords = Request.Form["tags"].Trim();
						news.Content = Request.Form["content"].Trim();
						context.SubmitChanges();

						Response.Redirect("news.aspx?start=" + start + "&limit=" + limit, true);
					} else
					{
						context.News.InsertOnSubmit(new db.News
						{
							Title = Request.Form["title"].Trim(),
							Keywords = Request.Form["tags"].Trim(),
							Content = Request.Form["content"].Trim(),
							Author = Common.User.AccountName// (Session["User"] as db.Account).AccountName
						});
						context.SubmitChanges();

						Response.Redirect("news.aspx", true);
					}
				}

				news_list.DataSource = context.News.Skip(start).Take(limit);
				news_list.DataBind();
				n_pager.Total = context.News.Count();
			}
		}
	}
}